package com.jiajia.study.chapter01.nio;

import com.jiajia.study.utils.ByteBufferUtil;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * String 和 ByteBuffer 相互转换
 * @author zjiajia
 * @date 2024/7/5 9:58
 */
public class TestByteBufferAndStringTransform {
    public static void main(String[] args) {
        testStringToByteBuffer();
        testByteBufferToString();
    }
    public static void testStringToByteBuffer(){
        // 方式一 : 字符集编码
        ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode("你好");
        ByteBufferUtil.debugAll(byteBuffer);

        ByteBuffer byteBuffer1 = Charset.forName("utf-8").encode("你好");
        ByteBufferUtil.debugAll(byteBuffer1);
        // 字符集解码
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
        // charBuffer toString 直接转成 String
        System.out.println(charBuffer.toString());

        // 方式二
        ByteBuffer byteBuffer2 = ByteBuffer.allocate(16);
        byteBuffer2.put("你好".getBytes(StandardCharsets.UTF_8));

        // 方式三
        ByteBuffer byteBuffer3 = ByteBuffer.wrap("你好".getBytes(StandardCharsets.UTF_8));
    }

    public static void testByteBufferToString(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        byteBuffer.put("你好".getBytes(StandardCharsets.UTF_8));

        String str = StandardCharsets.UTF_8.decode(byteBuffer).toString();
        System.out.println(str);

    }
}
